#!/usr/bin/python2
# -*- coding: utf-8 -*-

import os, re
from PySide import QtCore, QtGui
from utils import fixsvg, dict2obj, SVG_UNKNOWN_STRUC, tr
from widgets import svg2qimage

DataStoreRole = QtCore.Qt.UserRole + 1


regx_svg_text = re.compile(r'< */? *[sS][vV][gG] *>?')

class ListModel_1(QtCore.QAbstractListModel):
    def __init__(self, datain, parent = None, *args):
        QtCore.QAbstractListModel.__init__(self, parent, *args)
        self.listdata = []
        for l in datain:
            self.listdata.append(dict2obj(l))
            self.listdata[-1].checked = False

    def set_data(self, datain):
        self.listdata = []
        for l in datain:
            self.listdata.append(dict2obj(l))
            self.listdata[-1].checked = False
        self.reset()

    def rowCount(self, parent = QtCore.QModelIndex()):
        return len(self.listdata)

    def columnCount(self, parent = QtCore.QModelIndex()):
        pass

    def data(self, index, role = QtCore.Qt.DisplayRole):
        if not index.isValid(): return None
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            return self.listdata[index.row()].text
        elif role == DataStoreRole:
            return self.listdata[index.row()].data
        elif role == QtCore.Qt.CheckStateRole:
            if self.listdata[index.row()].checked:
                return QtCore.Qt.Checked
            return QtCore.Qt.Unchecked
        return None

    def setChecked(self, index, value = True):
        '''index: int'''
        self.listdata[index].checked = value
        self.reset()

    def setData(self, index, value, role):
        if role == QtCore.Qt.CheckStateRole:
            self.listdata[index.row()].checked = not self.listdata[index.row()].checked
        elif role == QtCore.Qt.EditRole:
            self.listdata[index.row()].text = value

        self.emit(QtCore.SIGNAL("dataChanged(QtCore.QModelIndex, QtCore.QModelIndex)"), index, index)
        return True

    def flags(self, index):
        return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | \
                QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEditable

class ListModel_2(QtCore.QAbstractListModel):
    def __init__(self, datain, headerdata = [], parent = None, *args):
        QtCore.QAbstractListModel.__init__(self, parent, *args)
        self.headerdata = headerdata
        self.listdata = datain

    def set_data(self, datain):
        self.listdata = datain
        self.reset()

    def rowCount(self, parent = QtCore.QModelIndex()):
        return len(self.listdata)

    def columnCount(self, parent = QtCore.QModelIndex()):
        return 1

    def data(self, index, role = QtCore.Qt.DisplayRole):
        if not index.isValid(): return None
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            return '%s' %(self.listdata[index.row()].filter_line)
        elif role == DataStoreRole:
            return self.listdata[index.row()]
        return None

    def flags(self, index):
        return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled

class MyTableView(QtGui.QTableView):
    '''For structure results display'''
    def __init__(self, parent = None):
        QtGui.QTableView.__init__(self, parent)
        self.icon_size = QtCore.QSize(150, 150)
        self.column_width = (1, 155)
        self.row_height = (0, 150)
        self.model = None
        self.uiseted = False

    def setModel(self, model):
        QtGui.QTableView.setModel(self, model)
        self.model = model
        if not self.uiseted:
            self.setUi()
            self.uiseted = True

    def setUi(self):
        self.setIconSize(self.icon_size)
        self.setColumnWidth(self.column_width[0], self.column_width[1])
        if self.model:
            for row in xrange(self.model.rowCount()):
                self.setRowHeight(row, self.row_height[1])

class TableModel_1(QtCore.QAbstractTableModel):
    '''For structure results management'''
    def __init__(self, datain, headerdata, parent=None, *args):
        QtCore.QAbstractTableModel.__init__(self, parent, *args)
        self.arraydata = datain
        self.headerdata = headerdata
        self.icon_size = (150, 150)

    def rowCount(self, parent = QtCore.QModelIndex()):
        return len(self.arraydata)

    def columnCount(self, parent = QtCore.QModelIndex()):
        return len(self.headerdata)

    def data(self, index, role):
        if not index.isValid():
            return None
        elif role == QtCore.Qt.DisplayRole:
            if index.column() == self.columnCount() - 1:
                return tr('Save MOL')
            if index.column() == self.columnCount() - 2:
                return tr('Confirm Result')
            if index.column() != 1:
                return self.arraydata[index.row()][index.column()]
        elif role == QtCore.Qt.TextAlignmentRole:
            return QtCore.Qt.AlignCenter
        elif role == QtCore.Qt.DecorationRole:
            if index.column() == 1:
                string = self.arraydata[index.row()][index.column()]
                if os.path.exists(string) and not string.endswith('svg'):
                    qimage = QtGui.QImage(QtCore.QSize(self.icon_size[0], self.icon_size[1]),
                            QtGui.QImage.Format_ARGB32)
                    qimage.load(string)
                    return qimage
                elif len(regx_svg_text.findall(string)) == 2:
                    qimage = QtGui.QImage(QtCore.QSize(self.icon_size[0], self.icon_size[1]),
                            QtGui.QImage.Format_ARGB32)
                    svg2qimage(string, qimage)
                    return qimage
                qimage = QtGui.QImage(QtCore.QSize(self.icon_size[0], self.icon_size[1]),
                        QtGui.QImage.Format_ARGB32)
                qimage = svg2qimage(SVG_UNKNOWN_STRUC, qimage)
                return qimage #QtGui.QIcon(qimage)
        return None

    def headerData(self, col, orientation, role):
        if role == QtCore.Qt.DisplayRole and self.headerdata:
            if not self.headerdata: return None
            if orientation == QtCore.Qt.Horizontal:
                return self.headerdata[col]
            elif orientation == QtCore.Qt.Vertical:
                return str(col + 1)
        return None

    def flags(self, index):
        return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled

if __name__ == "__main__":

    import sys

    icon_size = (100, 100)

    class MainWindow(QtGui.QMainWindow):

        def __init__(self, parent = None):

            QtGui.QMainWindow.__init__(self, parent)

            widget = QtGui.QWidget(self)
            layout = QtGui.QGridLayout(widget)
            listView = QtGui.QListView()
            layout.addWidget(listView)

            tableView = MyTableView()
            tableView.icon_size = QtCore.QSize(icon_size[0], icon_size[1])
            #tableView.setShowGrid(False)
            layout.addWidget(tableView)

            da = [{'text': 'aaaa', 'data': {1:'yes'}},
                {'text': 'bbbb', 'data': ['hahh']},
                {'text': 'cccccccccccc', 'data': 'xixixi'}]

            list_model = ListModel_1(da)
            listView.setModel(list_model)


            dt = [[1,open('b.svg').read(),2,3],[3,'a.svg',5,6],[4,'portrait.png',8,9]]
            table_model = TableModel_1(dt, ['yes', 'no', 'haha', 'oooo'])
            tableView.column_width = (1, 150)
            tableView.row_height = (0, 150)
            tableView.setModel(table_model)
            tableView.setColumnWidth(0, 40)

            self.setCentralWidget(widget)

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


